package com.lb.shopguide.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseActivity;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.order.CommitOrderReplyBean;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.shopguide.ui.fragment.guide.pay.FragmentPayOrder;
import com.lb.shopguide.ui.fragment.guide.pay.FragmentPayResult;
import com.lb.shopguide.util.lb.BizUtil;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;
import me.yokeyword.fragmentation.SupportFragment;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/7/17.
 */

public class PayActivity extends BaseActivity {
    private CommitOrderReplyBean mReplyBean;
    private String mMemberCode;
    private boolean quickPayFlag;

    private LbReceiver mLbReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        initData();
        registerReceiver();
    }

    private void initData() {
        mLbReceiver = new LbReceiver();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        mReplyBean = (CommitOrderReplyBean) bundle.getSerializable(AppConstant.COMMIT_REPLY_BEAN);
        mMemberCode = bundle.getString(AppConstant.MEMBER_CODE);
        if (bundle.containsKey(AppConstant.QUICK_PAY_MODE)) {
            quickPayFlag = true;
        }

        loadRootFragment(R.id.fl_container, FragmentPayOrder.newInstance(mReplyBean, mMemberCode));
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return super.onCreateFragmentAnimator();
    }

    public class LbReceiver extends BroadcastReceiver {
        //{"actualPayMoney":"0.01","orderNum":"115651115003147240692003"}
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            CommitOrderReplyBean bean = null;
            try {
                JSONObject jsonObject = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                bean = new CommitOrderReplyBean();
                bean.setOrderNum(jsonObject.getString("orderNum"));
                bean.setOrderTotalMoney(Float.parseFloat(jsonObject.getString("actualPayMoney")));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (intent.getAction().equals(AppConstant.BROADCAST_PAID)) {
                sendRequestConfirmOrderPay(bean);
            } else if (intent.getAction().equals(AppConstant.BROADCAST_FAIL)) {
                ((SupportFragment) getTopFragment()).start(FragmentPayResult.newInstance(false, bean));
            }
        }
    }

    private void sendRequestConfirmOrderPay(final CommitOrderReplyBean bean) {
        HashMap hashMap = new HashMap();
        hashMap.put("orderNum", mReplyBean.getOrderNum());
        hashMap.put("payMode", mReplyBean.getPayMode());
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {
            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    ((SupportFragment) getTopFragment()).start(FragmentPayResult.newInstance(true, bean));
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        SimpleObserverOtherListener errorListener = new SimpleObserverOtherListener() {
            @Override
            public void onSessionOutOfDate() {

            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort("确认支付订单异常");
            }
        };
        ApiMethodGuide.confirmOrderPay(new SimpleLbObserver(listener, errorListener), body, this, ActivityEvent.PAUSE);
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConstant.BROADCAST_PAID);
        intentFilter.addAction(AppConstant.BROADCAST_FAIL);
        registerReceiver(mLbReceiver, intentFilter);
    }

    private void unRegisterReceiver() {
        if (mLbReceiver != null) {
            this.unregisterReceiver(mLbReceiver);
        }
    }

    public boolean isQuickPayFlag() {
        return quickPayFlag;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterReceiver();
    }
}
